package com.bzkj.basicinfo.service.impl.ncc;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.bzkj.basicinfo.domain.ncc.NccBasicDept;
import com.bzkj.basicinfo.domain.ncc.NccBasicDeptVo;
import com.bzkj.basicinfo.domain.ncc.dto.NccBasicDeptDto;
import com.bzkj.basicinfo.mapper.NccBasicDeptMapper;
import com.bzkj.basicinfo.service.ncc.NccBasicDeptService;
import com.bzkj.basicinfo.utils.DataBatchProcessorUtil;
import com.bzkj.basicinfo.utils.HttpClientUtils;
import com.bzkj.basicinfo.utils.NccBasicUtil;
import com.bzkj.basicinfo.utils.UniqueIdentifierGenerator;
import com.bzkj.common.core.domain.AjaxResult;
import com.bzkj.common.core.domain.R;
import com.bzkj.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

/**
 * 普锐特下属部门信息：13
 */
@Service("nccJobNccBasicDeptService")
@Slf4j
public class NccBasicDeptServiceImpl implements NccBasicDeptService
{
    @Autowired
    private NccBasicDeptMapper nccBasicDeptMapper;
    @Autowired
    private NccBasicUtil nccBasicUtil;
    @Value("${ncc.baseUrl}")
    private static String baseUrl;

    @Value("${ncc.sourceSystem}")
    private static String sourceSystem;

    @Value("${ncc.basicInfoUrl}")
    private String basicInfoUrl;

    @Value("${ncc.targetSystem}")
    private static String targetSystem;

    @Value("${ncc.serviceName}")
    private static String serviceName;

    @Value("${ncc.contentType}")
    private static String contentType;

    @Value("${pk_org.code}")
    private Integer pkOrgCode;

    @Autowired
    private UniqueIdentifierGenerator uniq;

    @Override
    public void updateNccBasicDeptJob(String all)
    {
        if("all".equals(all)) {
            nccBasicUtil.ncc(13, pkOrgCode);
        } else {
            HttpResponse response = methodExecute(13);
            if(response.isOk()) {
                String responseBody = response.body();
                JSONObject entries = JSONUtil.parseObj(responseBody);
                JSONArray dataArray = entries.getJSONArray("data");
                List<NccBasicDept> nccBasicDepts = dataArray.toList(NccBasicDept.class);
                for(NccBasicDept nccBasicDept : nccBasicDepts) {
                    NccBasicDept basicDept = nccBasicDeptMapper.queryNccBasicDept(nccBasicDept.getCode());
                    if(basicDept != null) {
                        nccBasicDeptMapper.updateNccBasicDept(nccBasicDept);
                    } else {
                        nccBasicDeptMapper.insertNccBasicDept(nccBasicDept);
                    }
                }
            }
        }
    }

    /**
     * 分页查询部门信息
     *
     * @Author wangzhichao
     * @Date 2024/12/09 13:19:17
     * @Param dto
     */
    @Override
    public List<NccBasicDept> findNccBasicDeptData(NccBasicDeptDto dto)
    {
        return nccBasicDeptMapper.findNccBasicDeptData(dto);
    }

    /**
     * 根据pkDept修改部门状态
     *
     * @Author wangzhichao
     * @Date 2024/12/09 13:34:53
     * @Param status
     * @Param pkDept
     */
    @Override
    public AjaxResult nccBasicDeptEnableStatusUpdate(String status, String code)
    {
        try {
            int i = nccBasicDeptMapper.nccBasicDeptEnableStatusUpdate(status, code);
            return i > 0 ? AjaxResult.success("修改成功") : AjaxResult.error("修改失败");
        } catch(Exception e) {
            log.error("修改失败:{}", e);
            return AjaxResult.error("修改失败");
        }
    }

    /**
     * 根据code修改部门信息
     *
     * @Author wangzhichao
     * @Date 2024/12/09 13:44:18
     * @Param entity
     */
    @Override
    public AjaxResult nccBasicDeptDataUpdate(NccBasicDept entity)
    {
        NccBasicDept one = nccBasicDeptMapper.findNccBasicDeptByCode(entity.getCode());

        if(Objects.isNull(one)) {
            try {
                nccBasicDeptMapper.updateNccBasicDept(entity);
                return AjaxResult.success("修改成功");
            } catch(Exception e) {
                log.error("修改失败:{}", e);
                return AjaxResult.error("修改失败");
            }
        } else {
            if(one.getPkDept().equals(entity.getPkDept())){
                nccBasicDeptMapper.updateNccBasicDept(entity);
                return AjaxResult.success("修改成功");
            }else{
                return AjaxResult.error("修改失败code重复");
            }
        }

    }

    /**
     * 新增部门信息
     *
     * @Author wangzhichao
     * @Date 2024/12/10 08:54:53
     * @Param entity
     */
    @Override
    public AjaxResult nccBasicDeptSave(NccBasicDept entity)
    {
        NccBasicDept one = nccBasicDeptMapper.findNccBasicDeptByCode(entity.getCode());

        if(Objects.isNull(one)) {
            String userName = SecurityUtils.getLoginUser().getUser().getUserName();
            entity.setPkGroup("0001A1100000000021CH");
            entity.setCreator(userName);
            entity.setModifier(userName);
            entity.setCreationTime(new Date());
            entity.setModifiedTime(new Date());
            try {
                String deptKey = "WMS" + uniq.generateUniqueIdentifier();
                entity.setPkDept(deptKey);
                nccBasicDeptMapper.insertNccBasicDept(entity);
                return AjaxResult.success("新增成功");
            } catch(Exception e) {
                log.error("新增失败:{}", e);
                return AjaxResult.error("新增失败");
            }
        } else {
            return AjaxResult.error("部门代码重复");
        }
    }

    @Override
    public R findDeptListByName(String name)
    {
        List<NccBasicDeptVo> nccBasicDept = nccBasicDeptMapper.findDeptListByName(name);
        return R.ok(nccBasicDept);
    }

    @Autowired
    private HttpClientUtils hcu;

    /**
     * 定时同步当天部门信息
     * @return
     */
    @Override
    public R jobMethodExecute(Boolean flag)
    {
        HashMap<String, String> searchDate = DataBatchProcessorUtil.getSearchDate(flag);

        // 查询当前数据
        HttpResponse response = hcu.methodExecute(searchDate.get("startTimeStr"), searchDate.get("endTimeStr"), 13, pkOrgCode);
        com.alibaba.fastjson2.JSONObject jsonNode = JSON.parseObject(response.body());
        // 收集rep系统数据
        List<NccBasicDept> list = jsonNode.getJSONArray("data").toJavaList(NccBasicDept.class);
        if(! list.isEmpty())
            extracted(list);

        return R.ok("同步成功");
    }

    /**
     * 批量更新或者插入
     *
     * @Date 2024/12/11 14:17:12
     * @Param list
     */
    @Transactional(rollbackFor = Exception.class)
    public void extracted(List<NccBasicDept> list)
    {
        for (NccBasicDept nccBasicDept : list) {
            nccBasicDeptMapper.insertOrUpdate(nccBasicDept);
        }
    }


    /**
     * 公有方法抽取
     *
     * @param i
     * @return
     */
    public HttpResponse methodExecute(Integer i)
    {
        //        String url = NccHttpUtils.getUrl();
        HashMap<String, Object> hashMap = new HashMap<>();
        // 定义时间格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 获取昨天的日期
        LocalDate yesterday = LocalDate.now().minusDays(1);
        // 昨天的00:00
        LocalDateTime startOfYesterday = yesterday.atStartOfDay();
        String startOfYesterdayStr = startOfYesterday.format(formatter);
        // 昨天的23:59:59
        LocalDateTime endOfYesterday = yesterday.atTime(23, 59, 59);
        String endOfYesterdayStr = endOfYesterday.format(formatter);
        //        添加post请求参数
        hashMap.put("startTime", startOfYesterdayStr);

        //        hashMap.put("startTime", "2022-01-01 02:32:20");
        hashMap.put("endTime", endOfYesterdayStr);
        hashMap.put("nccBaseDataEnum", i);
        hashMap.put("platformCode", "111");
        String jsonString = JSONUtil.toJsonStr(hashMap);

        // 添加请求头
        HttpResponse response = HttpUtil.createPost(basicInfoUrl).header("sourceSystem", sourceSystem).header("targetSystem", targetSystem).header("serviceName", serviceName).header("contentType", contentType).body(jsonString, "application/json").execute();
        return response;
    }
}
